package it.michaellinker.msr.web.util.metric.counter;

import java.util.HashMap;
import java.util.Map;

/**
 * Counter based on map.
 *
 * @param <T> The type of object to count.
 */
public class MapCounter<T> implements RequestCounter<T> {
    private static final long COUNTER_INITIAL_VALUE = 0L;
    private final Map<T, Long> counterMap;

    public MapCounter() {
        counterMap = new HashMap<>();
    }

    @Override
    public synchronized void count(T key) {
        long counter = counterMap.getOrDefault(key, COUNTER_INITIAL_VALUE);
        counterMap.put(key, counter + 1);
    }

    @Override
    public synchronized Map<T, Long> getResult() {
        Map<T, Long> bufferCounterMap;
        bufferCounterMap = new HashMap<>(counterMap);
        counterMap.clear();
        return bufferCounterMap;
    }
}
